<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>确认订单</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        :root {
            --primary-color: #FFB74D; /* 主色调：暖橙色 */
            --primary-light: #FFE0B2; /* 浅色调：淡橙色 */
            --primary-dark: #F57C00;  /* 深色调：深橙色 */
            --bg-color: #FFF8E1;      /* 背景色：淡黄色 */
            --card-bg: #FFFFFF;       /* 卡片背景：白色 */
            --text-primary: #5D4037;  /* 主要文字：深棕色 */
            --text-secondary: #8D6E63;/* 次要文字：棕色 */
        }

        body {
            background-color: var(--bg-color);
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            color: var(--text-primary);
        }

        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
        }

        .order-section {
            background: var(--card-bg);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(243, 156, 18, 0.1);
            border: 1px solid var(--primary-light);
            transition: transform 0.3s ease;
        }

        .order-section:hover {
            transform: translateY(-2px);
        }

        .section-title {
            font-size: 18px;
            color: var(--text-primary);
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-light);
        }

        .address-info {
            display: flex;
            align-items: flex-start;
            padding: 15px;
            background: var(--bg-color);
            border-radius: 4px;
            border: 1px solid var(--primary-color);
        }

        .address-icon {
            color: var(--primary-color);
            margin-right: 15px;
            font-size: 20px;
        }

        .address-details {
            flex: 1;
        }

        .address-name {
            font-weight: bold;
            color: var(--text-primary);
            margin-bottom: 5px;
        }

        .product-info {
            display: flex;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .product-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            margin-right: 15px;
            border-radius: 4px;
        }

        .product-details {
            flex: 1;
        }

        .product-name {
            font-size: 16px;
            margin-bottom: 10px;
        }

        .product-price {
            color: var(--primary-dark);
            font-size: 18px;
            font-weight: bold;
        }

        .order-summary {
            text-align: right;
        }

        .price-row {
            margin: 10px 0;
            color: var(--text-secondary);
        }

        .total-price {
            font-size: 20px;
            color: var(--primary-dark);
            font-weight: bold;
        }

        .submit-btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 20px;
            width: 100%;
            transition: all 0.3s ease;
        }

        .submit-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .address-list {
            display: none;
            margin-top: 15px;
        }

        .address-item {
            padding: 15px;
            border: 1px solid var(--primary-light);
            margin-bottom: 10px;
            border-radius: 4px;
            cursor: pointer;
            background: var(--card-bg);
            transition: all 0.3s ease;
        }

        .address-item:hover {
            background: var(--bg-color);
            transform: translateY(-2px);
        }

        .address-item.selected {
            border: 2px solid var(--primary-color);
            background: var(--bg-color);
        }

        .show-more {
            color: var(--primary-color);
            cursor: pointer;
            text-align: center;
            padding: 10px;
            margin-top: 10px;
            transition: all 0.3s ease;
        }

        .show-more:hover {
            color: var(--primary-dark);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="order-section">
            <div class="section-title">收货地址</div>
            <div class="address-info" id="defaultAddress">
                <i class="fas fa-map-marker-alt address-icon"></i>
                <div class="address-details">
                    <div class="address-name">收货人：<span id="receiverName">加载中...</span></div>
                    <div class="address-phone">电话：<span id="receiverPhone">加载中...</span></div>
                    <div class="address-text">地址：<span id="receiverAddress">加载中...</span></div>
                </div>
            </div>
            <div class="show-more" onclick="toggleAddressList()">
                <span id="showMoreText">显示更多地址</span> <i class="fas fa-chevron-down"></i>
            </div>
            <div class="address-list" id="addressList">
                <!-- 这里将通过JavaScript动态添加地址列表 -->
            </div>
        </div>

        <div class="order-section">
            <div class="section-title">商品信息</div>
            <div class="product-info">
                <img src="" alt="商品图片" class="product-image" id="productImage">
                <div class="product-details">
                    <div class="product-name" id="productName">加载中...</div>
                    <div class="product-price">¥<span id="productPrice">0.00</span></div>
                </div>
            </div>
        </div>

        <div class="order-section">
            <div class="section-title">订单信息</div>
            <div class="order-summary">
                <div class="price-row">
                    商品金额：¥<span id="subtotal">0.00</span>
                </div>
                <div class="price-row">
                    运费：¥<span id="shipping">0.00</span>
                </div>
                <div class="total-price">
                    实付款：¥<span id="total">0.00</span>
                </div>
            </div>
            <button class="submit-btn" onclick="submitOrder()">提交订单</button>
        </div>
    </div>

    <script>
        // 生成订单号函数
        function generateOrderNo() {
            const now = new Date();
            const year = now.getFullYear().toString().slice(-2);
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
            
            return `DD${year}${month}${day}${hours}${minutes}${seconds}${random}`;
        }

        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const productId = urlParams.get('pid');

        // 加载商品信息
        $.ajax({
            url: "/product/detail",
            type: "GET",
            data: { id: productId },
            success: function(response) {
                if(response.state === 1) {
                    console.log(response.data);
                    const product = response.data[0];
                    $('#productName').text(product.name);
                    $('#productPrice').text(product.price);
                    $('#productImage').attr('src', JSON.parse(product.images)[0]);
                    $('#subtotal').text(product.price);
                    $('#shipping').text(product.shippingFee);
                    $('#total').text(product.price + product.shippingFee);
                    window.productData = product;
                }
            }
        });

        let allAddresses = [];
        let isAddressListVisible = false;

        // 加载收货地址
        $.ajax({
            url: "/user/get-addresses",
            type: "GET",
            success: function(response) {
                if(response.state === 1) {
                    console.log(response.data);
                    allAddresses = response.data;
                    if(allAddresses && allAddresses.length > 0) {
                        // 显示默认地址（第一个地址）
                        showAddress(allAddresses[0]);
                        // 渲染地址列表
                        renderAddressList();
                    } else {
                        alert('请先添加收货地址');
                        location.href = 'setting.html';
                    }
                }
            },
            error: function() {
                alert('获取地址信息失败,请先登录');
                location.href = 'login.html';
            }
        });

        // 显示单个地址
        function showAddress(address) {
            $('#receiverName').text(address.recipientName);
            $('#receiverPhone').text(address.recipientPhone);
            $('#receiverAddress').text(address.address || '未设置详细地址');
        }

        // 渲染地址列表
        function renderAddressList() {
            const addressList = $('#addressList');
            addressList.empty();
            
            allAddresses.forEach((address, index) => {
                const addressHtml = `
                    <div class="address-item ${index === 0 ? 'selected' : ''}" 
                         data-id="${address.id}"
                         onclick="selectAddress(${index})">
                        <div class="address-name">${address.recipientName}</div>
                        <div class="address-phone">${address.recipientPhone}</div>
                        <div class="address-text">${address.address || '未设置详细地址'}</div>
                    </div>
                `;
                addressList.append(addressHtml);
            });
        }

        // 切换地址列表显示状态
        function toggleAddressList() {
            isAddressListVisible = !isAddressListVisible;
            const addressList = $('#addressList');
            const showMoreText = $('#showMoreText');
            
            if(isAddressListVisible) {
                addressList.slideDown();
                showMoreText.text('收起地址');
            } else {
                addressList.slideUp();
                showMoreText.text('显示更多地址');
            }
        }

        // 选择地址
        function selectAddress(index) {
            const address = allAddresses[index];
            showAddress(address);
            
            // 更新选中状态
            $('.address-item').removeClass('selected');
            $('.address-item').eq(index).addClass('selected');
            
            // 关闭地址列表
            toggleAddressList();
        }

        // 提交订单
        function submitOrder() {
            // 获取选中的地址ID
            const selectedAddress = $('.address-item.selected');
            if (!selectedAddress.length) {
                alert('请选择收货地址');
                return;
            }

            const orderData = {
                productId: productId,
                orderNo: generateOrderNo(),
                sellerId: window.productData.sellerId,  // 添加卖家ID
                totalPrice: window.productData.price + window.productData.shippingFee,  // 使用商品价格加运费
                receivingId: parseInt(selectedAddress.data('id')),
                brandName: window.productData.brand
            };

            console.log("提交订单数据：", orderData);

            $.ajax({
                url: "/order/create",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(orderData),
                success: function(response) {
                    if(response.state === 1) {

                        window.open(`https://vdmgkmgxkljg.sealoshzh.site/alipay/pay?traceNo=${orderData.orderNo}&totalAmount=${orderData.totalPrice}&subject=${orderData.brandName}`, '_blank');
                    } else {
                        console.log(orderData);
                        alert(response.msg || '创建订单失败');
                    }
                },
                error: function() {
                    alert('创建订单失败，请稍后重试');
                }
            });
        }
    </script>
</body>
</html> 